// HTTP请求配置
const httpConfig = {
  baseURL: process.env.UNI_PLATFORM === 'h5' ? '/api' : '',  // H5模式使用代理前缀，其他模式使用完整URL
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
};

// 检查URL是否为完整的HTTP(S)地址
function isFullUrl(url) {
  return /^https?:\/\/.+/.test(url);
}

// 创建HTTP请求
export async function request(options) {
  const { url, method = 'GET', data, headers = {} } = options;

  try {
    const requestHeaders = {
      ...httpConfig.headers,
      ...headers
    };

    if (method === 'GET') {
      requestHeaders['X-Requested-With'] = 'XMLHttpRequest';
      requestHeaders['Accept'] = 'application/json';
    }

    // Ensure proper URL construction
    let fullUrl = isFullUrl(url) ? url : url.startsWith('/') ? httpConfig.baseURL + url : httpConfig.baseURL + '/' + url;

    const requestOptions = {
      url: fullUrl,
      method,
      header: requestHeaders,
      dataType: 'json'
    };

    if (data) {
      if (method === 'GET') {
        const params = Object.entries(data)
          .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
          .join('&');
        requestOptions.url += `?${params}`;
      } else {
        requestOptions.data = data;
      }
    }

    return new Promise((resolve, reject) => {
      console.log('发送请求:', requestOptions);
      uni.request(requestOptions).then(
        (response) => {
          console.log('收到响应:', response);
          if (response.statusCode === 200) {
            resolve(response.data);
          } else {
            const errorMsg = response.statusCode === 404
              ? `请求的资源不存在 (${requestOptions.url})`
              : `请求失败 (状态码: ${response.statusCode})`;
            console.error('请求错误:', errorMsg);
            reject(new Error(errorMsg));
          }
        }
      ).catch(
        (error) => {
          console.error('请求异常:', error);
          reject(error);
        }
      );
    });
  } catch (error) {
    throw error;
  }
}

// 更新HTTP配置
export function updateHttpConfig(config) {
  // 根据运行环境设置baseURL
  if (config.url && config.port) {
    httpConfig.baseURL = process.env.UNI_PLATFORM === 'h5' 
      ? '/api'  // H5模式使用代理前缀
      : `http://${config.url}:${config.port}`;  // 其他模式使用完整URL
  }

  // 更新其他配置项
  const allowedKeys = ['timeout', 'headers'];
  Object.keys(config)
    .filter(key => allowedKeys.includes(key))
    .forEach(key => {
      if (key === 'headers') {
        // 合并headers而不是完全替换
        httpConfig.headers = {
          ...httpConfig.headers,
          ...config.headers
        };
      } else {
        httpConfig[key] = config[key];
      }
    });
  return httpConfig;
}